#! /usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import serial
import time
import Queue
import json
import config


class Serial(object):
    def __init__(self, ByteSize="8", Parity="N", Stopbits="1"):
        '''
        串行口初始化函数

        :param ByteSize:数据位
        :param Parity:校验位
        :param Stopbits:停止位
        '''
        self.l_serial = None
        self.l_serial = serial.Serial()
        self.alive = False
        self.bytesize = ByteSize
        self.parity = Parity
        self.stopbits = Stopbits
        self.thresholdValue = 64
        self.receive_data = ""

    def start(self, serialPort, baudRate):
        '''
        打开串行口，这里选择只传入两个参数

        :param serialPort: 串口号名称
        :param baudRate: 串口波特率
        :return:
        '''
        self.l_serial = serial.Serial()
        self.l_serial.port = serialPort
        self.l_serial.baudrate = baudRate
        self.l_serial.bytesize = int(self.bytesize)
        self.l_serial.parity = self.parity
        self.l_serial.stopbits = int(self.stopbits)
        self.l_serial.timeout = 0.01

        try:
            self.l_serial.open()
            if self.l_serial.isOpen():
                self.alive = True
        except Exception as e:
            self.alive = False

    def stop(self):
        '''
        关闭串口

        :return:
        '''
        self.alive = False
        if self.l_serial.isOpen():
            self.l_serial.close()

    def read(self, q):
        '''
        读取串行口数据，传入一个queue对象，然后串口就会把数据写入队列中

        当收到换行符之后才会把数据写入Queue中
        :param q: Queue对象，由另外一个线程消费
        :return:
        '''
        while self.alive:
            while self.l_serial.inWaiting() > 0:
                self.receive_data += self.l_serial.read(1)
                time.sleep(0.0001)
            if self.receive_data != '':
                q.put(self.receive_data)
                self.receive_data = ''

    def write(self, data):
        '''
        向串口写入数据

        :param data: 待写入的数据
        :return: 0 写入成功/ -1 写入失败
        '''
        if self.alive:
            if self.l_serial.isOpen():
                self.l_serial.write(data)
                return 0
            else:
                return -1


ser = Serial()


def send_data(data):
    ser.write(data)


def serial_init():
    '''
    串口初始化函数

    :return:
    '''
    q = Queue.Queue()
    ser.start(config.UART_PORT, config.UART_BAUD_RATE)
    thread_read = threading.Thread(target=ser.read, args=(q,))
    recvQ = threading.Thread(target=serial_recv_queue, args=(q,))
    thread_read.start()
    recvQ.start()
    print("Init serialport ok!")
    q.join()


import mq


# 串口接收队列,串口把生产的的数据写入Queue,在此处消费数据
def serial_recv_queue(q):
    """
    线程worker函数
    用于处理队列中的元素项，这些守护线程在一个无限循环中，只有当主线程结束时才会结束循环
    """
    while True:
        data = q.get()
        if len(data) > 1:
            try:
                if data.startswith("{'chip_id':'?'}"):
                    ser.write("{'chip_id':'" + str(config.CHPIP_ID) + "'}")
                else:
                    print(data)
                    try:
                        jsondata = json.loads(data)
                        print(jsondata['id'])
                        mq.send_msg(jsondata['id'], data)
                    except:
                        print("parse jsondata error!")
            except TypeError:
                print("Serial Data is None!")


if __name__ == "__main__":
    serial_init()



# {"id": "er/6636366/12345", "type": "s", "stype": "temp", "data": "025"}
